<template>
  <div class="bi-avatar" :style="{ background: color }">
    <span ref="children" :style="childrenStyle">
      <slot></slot>
    </span>
  </div>
</template>

<script>
export default {
  name: 'BiAvatar',
  props: {
    size: {
      type: String,
      default: 'small'
    }
  },
  data() {
    return {
      scale: 1,
      childrenWidth: 0,
      colorList: ['#f56a00', '#7265e6', '#ffbf00', '#00a2ae'],
      color: '#f56a00'
    }
  },
  computed: {
    childrenStyle() {
      return {
        msTransform: `scale(${this.scale})`,
        WebkitTransform: `scale(${this.scale})`,
        transform: `scale(${this.scale})`,
        position: 'absolute',
        display: 'inline-block',
        left: `calc(50% - ${Math.round(this.childrenWidth / 2)}px)`
      }
    }
  },
  mounted() {
    this.setScale()
    this.handleColorChange()
    console.log(this.$refs.children.innerText)
  },
  updated() {
    this.setScale()
    this.handleColorChange()
  },
  methods: {
    setScale() {
      if (this.$refs.children) {
        // set children width again to make slot centered
        this.childrenWidth = this.$refs.children.offsetWidth
        const avatarWidth = this.$el.getBoundingClientRect().width
        // add 4px gap for each side to get better performance
        if (avatarWidth - 8 < this.childrenWidth) {
          this.scale = (avatarWidth - 8) / this.childrenWidth
        } else {
          this.scale = 1
        }
      }
    },
    handleColorChange() {
      const len = this.$refs.children.innerText.length || 0
      const index = len % 5
      this.color = this.colorList[index] || '#f56a00'
      return this.color
    }
  }
}
</script>

<style lang="scss" scoped>
.bi-avatar {
  box-sizing: border-box;
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
  border-radius: 16px;
}
</style>
